package com.dzl.enterprise;

import com.dzl.admin.pojo.vo.LoginSysAdminVo;
import com.dzl.base.controller.BaseController;
import com.dzl.constant.UploadConstant;
import com.dzl.enterprise.pojo.dto.*;
import com.dzl.userwx.pojo.WelfareUserOrganization;
import com.dzl.userwx.pojo.WelfareUserWx;
import com.dzl.userwx.pojo.query.UserOrganizationQuery;
import com.dzl.enterprise.pojo.vo.WelfareEnterpriseOrganizationTreeVo;
import com.dzl.userwx.pojo.vo.WelfareUserOrganizationVo;
import com.dzl.enterprise.service.WelfareEnterpriseOrganizationService;
import com.dzl.userwx.service.WelfareUserOrganizationService;
import com.dzl.userwx.service.WelfareUserWxService;
import com.dzl.util.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * 企业组织信息表(WelfareEnterpriseOrganization)表控制层
 * @author ChenLong
 * @date 2021-09-07 15:28:26
 */
@Slf4j
@RestController
@RequestMapping("/welfareEnterpriseOrganization")
public class WelfareEnterpriseOrganizationController extends BaseController {

    @Autowired
    private WelfareEnterpriseOrganizationService service;
    @Autowired
    private WelfareUserOrganizationService welfareUserOrganizationService;
    @Autowired
    private WelfareUserWxService welfareUserWxService;

    /**
     * 获取组织下用户列表
     * @author ChenLong
     * @date 2021-09-08 17:52:57
     * @param query 组织
     * @return java.util.List<java.lang.Integer>
     **/
    @GetMapping("getOrganizationUserList")
    public PageUtils<WelfareUserOrganizationVo> getOrganizationUserList(UserOrganizationQuery query) {
        log.info("getOrganizationUserList in: " + query.toString());
        LoginSysAdminVo adminInfo = getAdminInfo();
        query.setEnterpriseId(adminInfo.getEnterpriseId());
        PageInfo<WelfareUserOrganizationVo> pageInfo = new PageInfo<>(welfareUserOrganizationService.getOrganizationUserList(query));
        return new PageUtils<>(pageInfo);
    }

    /**
     * 获取企业的组织架构树
     * @author ChenLong
     * @date 2021-09-13 18:58:39
     * @param enterpriseId 企业Id
     * @return com.dzl.util.JsonResult<java.util.List<com.dzl.enterprise.pojo.vo.WelfareEnterpriseOrganizationTreeVo>>
     **/
    @GetMapping("getEnterpriseOrganizationTree")
    public JsonResult<List<WelfareEnterpriseOrganizationTreeVo>> getEnterpriseOrganizationTree(Integer enterpriseId) {
        log.info("getEnterpriseOrganizationTree in: " + enterpriseId);
        return JsonResult.success(service.getEnterpriseOrganizationTree(enterpriseId));
    }

    /**
     * 登陆密码重置
     * @author ChenLong
     * @date 2021-09-13 18:58:46
     * @param userId 用户ID
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     **/
    @PostMapping("updatePassWordReset")
    public JsonResult<Integer> updatePassWordReset(Integer userId){
        log.info("updatePassWordReset in: " + userId);
        WelfareUserWx welfareUserWxUpd = new WelfareUserWx();
        welfareUserWxUpd.setPassword(PasswordUtil.AESEncrypt("123456"));
        welfareUserWxUpd.setId(userId);
        return JsonResult.success(welfareUserWxService.updateByPrimaryKeySelective(welfareUserWxUpd));
    }

    /**
     * 支付密码重置
     * @author ChenLong
     * @date 2021-09-13 18:58:51
     * @param userId 用户ID
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     **/
    @PostMapping("updatePayPassWordReset")
    public JsonResult<Integer> updatePayPassWordReset(Integer userId){
        log.info("updatePayPassWordReset in: " + userId);
        WelfareUserWx welfareUserWxUpd = new WelfareUserWx();
        welfareUserWxUpd.setPayPassword(PasswordUtil.AESEncrypt("1234"));
        welfareUserWxUpd.setId(userId);
        return JsonResult.success(welfareUserWxService.updateByPrimaryKeySelective(welfareUserWxUpd));
    }

    /**
     * 添加组织架构信息
     * @param enterpriseOrganizationAddDto 组织信息dto
     * @return Integer 是否成功
     * @author ChenLong
     * @date 2021-09-07 17:37:38
     **/
    @PostMapping("addEnterpriseOrganization")
    public JsonResult<Integer> addEnterpriseOrganization(@RequestBody EnterpriseOrganizationAddDto enterpriseOrganizationAddDto) {
        log.info("addEnterpriseOrganization in");
        if (EmptyUtils.isEmpty(enterpriseOrganizationAddDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(enterpriseOrganizationAddDto.getEnterpriseId())) {
            return JsonResult.paramErrWithMsg("无效企业");
        }
        if (enterpriseOrganizationAddDto.getParentId()==null) {
            return JsonResult.paramErrWithMsg("无效根目录");
        }
        if (EmptyUtils.isEmpty(enterpriseOrganizationAddDto.getLevel())) {
            return JsonResult.paramErrWithMsg("无效级别");
        }
        if (EmptyUtils.isEmpty(enterpriseOrganizationAddDto.getName())) {
            return JsonResult.paramErrWithMsg("请填写组织名");
        }
        return JsonResult.success(service.addEnterpriseOrganization(enterpriseOrganizationAddDto));
    }

    /**
     * 更新组织架构信息
     * @param enterpriseOrganizationUpdDto 组织信息dto
     * @return void
     * @author ChenLong
     * @date 2021-09-07 17:37:38
     **/
    @PostMapping("updateEnterpriseOrganization")
    public JsonResult<Integer> updateEnterpriseOrganization(@RequestBody EnterpriseOrganizationUpdDto enterpriseOrganizationUpdDto) {
        log.info("updateEnterpriseOrganization in");
        if (EmptyUtils.isEmpty(enterpriseOrganizationUpdDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(enterpriseOrganizationUpdDto.getId())) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(enterpriseOrganizationUpdDto.getName())) {
            return JsonResult.paramErrWithMsg("请填写组织名");
        }
        return JsonResult.success(service.updateEnterpriseOrganization(enterpriseOrganizationUpdDto));
    }

    /**
     * 删除组织架构信息
     * @param enterpriseOrganizationDelDto 组织信息dto
     * @return void
     * @author ChenLong
     * @date 2021-09-07 17:37:38
     **/
    @PostMapping("deleteEnterpriseOrganization")
    public JsonResult<Integer> deleteEnterpriseOrganization(@RequestBody EnterpriseOrganizationDelDto enterpriseOrganizationDelDto) {
        log.info("deleteEnterpriseOrganization in");
        if (EmptyUtils.isEmpty(enterpriseOrganizationDelDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(enterpriseOrganizationDelDto.getId())) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(enterpriseOrganizationDelDto.getLevel())) {
            return JsonResult.paramErrWithMsg("无效级别");
        }
        enterpriseOrganizationDelDto.setEnterpriseId(getWxUserInfo().getEnterpriseId());
        return JsonResult.success(service.deleteEnterpriseOrganization(enterpriseOrganizationDelDto));
    }

    /**
     * 添加用户信息
     * @param organizationUserAddDto 用户组织dto
     * @author ChenLong
     * @date 2021-09-07 17:55:36
     **/
    @PostMapping("addUserForEnterpriseOrganization")
    public JsonResult<Integer> addUserForEnterpriseOrganization(@RequestBody OrganizationUserAddDto organizationUserAddDto) {
        log.info("addUserForEnterpriseOrganization in");
        LoginSysAdminVo adminInfo = getAdminInfo();
        if (EmptyUtils.isEmpty(organizationUserAddDto.getName())) {
            return JsonResult.paramErrWithMsg("请填写用户名");
        }
        if (EmptyUtils.isEmpty(organizationUserAddDto.getPhone())) {
            return JsonResult.paramErrWithMsg("请填写正确的账户信息");
        }
        organizationUserAddDto.setEnterpriseId(adminInfo.getEnterpriseId());
        return JsonResult.success(service.addUserForEnterpriseOrganization(organizationUserAddDto));
    }

    /**
     * 更新用户信息
     * @param organizationUserUpdDto 用户组织dto
     * @return void
     * @author ChenLong
     * @date 2021-09-07 17:55:36
     **/
    @PostMapping("updateUserForEnterpriseOrganization")
    public JsonResult<Integer> updateUserForEnterpriseOrganization(@RequestBody OrganizationUserUpdDto organizationUserUpdDto) {
        log.info("updateUserForEnterpriseOrganization in");
        LoginSysAdminVo adminInfo = getAdminInfo();
        if (EmptyUtils.isEmpty(organizationUserUpdDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        organizationUserUpdDto.setEnterpriseId(adminInfo.getEnterpriseId());
        if (EmptyUtils.isEmpty(organizationUserUpdDto.getId())) {
            return JsonResult.paramErrWithMsg("无效企业");
        }
        return JsonResult.success(service.updateUserForEnterpriseOrganization(organizationUserUpdDto));
    }

    /**
     * 删除用户信息
     * @param organizationUserUpdDto 用户组织dto
     * @return void
     * @author ChenLong
     * @date 2021-09-07 17:55:36
     **/
    @PostMapping("deleteUserForEnterpriseOrganization")
    public JsonResult<Integer> deleteUserForEnterpriseOrganization(@RequestBody OrganizationUserUpdDto organizationUserUpdDto) {
        log.info("deleteEnterpriseOrganization in");
        if (EmptyUtils.isEmpty(organizationUserUpdDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(organizationUserUpdDto.getId())) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        return JsonResult.success(service.deleteUserForEnterpriseOrganization(organizationUserUpdDto));
    }

    /**
     * 用户停用
     * @param organizationUserUpdDto 用户组织dto
     * @return void
     * @author ChenLong
     * @date 2021-09-07 17:55:36
     **/
    @PostMapping("updateUserStopUsed")
    public JsonResult<Integer> updateUserStopUsed(@RequestBody OrganizationUserUpdDto organizationUserUpdDto) {
        log.info("deleteEnterpriseOrganization in");
        if (EmptyUtils.isEmpty(organizationUserUpdDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(organizationUserUpdDto.getUserId())) {
            return JsonResult.paramErrWithMsg("无效用户");
        }
        if (EmptyUtils.isEmpty(organizationUserUpdDto.getIsUsed())) {
            return JsonResult.paramErrWithMsg("无效参数");
        }
        return JsonResult.success(service.updateUserStopUsed(organizationUserUpdDto));
    }

    /**
     * 批量调整组织架构
     * @author ChenLong
     * @date 2021-09-08 21:08:07
     * @param organizationUserUpdBatchDto 组织DTO
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     **/
    @PostMapping("updateBatchUserOrganization")
    public JsonResult<Integer> updateBatchUserOrganization(@RequestBody OrganizationUserUpdBatchDto organizationUserUpdBatchDto) {
        log.info("deleteEnterpriseOrganization in");
        if (EmptyUtils.isEmpty(organizationUserUpdBatchDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        if (EmptyUtils.isEmpty(organizationUserUpdBatchDto.getUserIdList())) {
            return JsonResult.paramErrWithMsg("请选择用户");
        }
        if (EmptyUtils.isEmpty(organizationUserUpdBatchDto.getUserOrganizationDto())) {
            return JsonResult.paramErrWithMsg("请选择组织");
        }
        organizationUserUpdBatchDto.getUserOrganizationDto().setEnterpriseId(getAdminInfo().getEnterpriseId());
        return JsonResult.success(service.updateBatchUserOrganization(organizationUserUpdBatchDto.getUserIdList(),organizationUserUpdBatchDto.getUserOrganizationDto()));
    }

    /**
     * 导入组织架构
     * @param list 行列表
     * @param orgId 企业组织Id
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     * @author ChenLong
     * @date 2021-09-07 15:33:01
     **/
    @RequestMapping("/importOrganization")
    public JsonResult<Integer> importOrganization(HttpServletRequest request) throws Exception {
        LoginSysAdminVo adminInfo = getAdminInfo();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        //文件名规则 用户D:\\memberExcel\\时间戳_memberId.后缀
        if (EmptyUtils.isEmpty(items)) {
            return new JsonResult<>(null, HttpCode.ERROR);
        }
        String fileName = items.get(0).getName();
        if (EmptyUtils.isEmpty(fileName)) {
            return new JsonResult<>(null, 101, "请上传文件");
        }
        StringBuffer newFileName = new StringBuffer();
        newFileName.append(UploadConstant.excel_path)
                .append(System.currentTimeMillis())
                .append("_")
                .append(adminInfo.getId())
                .append(fileName.substring(fileName.lastIndexOf("."), fileName.length()));
        File file = new File(newFileName.toString());
        if (file.exists()) {//文件存在就重新创建
            file.delete();
        }
        file = new File(newFileName.toString());
        file.createNewFile();
        InputStream is = items.get(0).getInputStream();
        //将原文件内容读取到目标文件
        OutputStream out = new FileOutputStream(file);
        try {
            int a = 0;
            while ((a = is.read()) != -1) {
                out.write(a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //流关闭
            try {
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JsonResult<List<List<String>>> data = ReadExcelUtil.readExcelInfo(file);
        if (data.getCode() != 200) {
            return new JsonResult<>(null, data.getCode(), data.getMsg());
        }
        return service.addImportOrganization(data.getData(), adminInfo.getEnterpriseId());
    }

    /**
     * 导入人员
     * @param list 行列表
     * @param orgId 企业组织Id
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     * @author ChenLong
     * @date 2021-09-07 15:33:01
     **/
    @RequestMapping("/importUserAndOrganization")
    public JsonResult<Integer> importUserAndOrganization(HttpServletRequest request,UserOrganizationDto userOrganizationDto) throws Exception {
        LoginSysAdminVo adminInfo = getAdminInfo();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        //文件名规则 用户D:\\memberExcel\\时间戳_memberId.后缀
        if (EmptyUtils.isEmpty(items)) {
            return new JsonResult<>(null, HttpCode.ERROR);
        }
        if (EmptyUtils.isEmpty(userOrganizationDto)) {
            return JsonResult.failWithMsg("请选择组织");
        }
        String fileName = items.get(0).getName();
        if (EmptyUtils.isEmpty(fileName)) {
            return new JsonResult<>(null, 101, "请上传文件");
        }
        StringBuffer newFileName = new StringBuffer();
        newFileName.append(UploadConstant.excel_path)
                .append(System.currentTimeMillis())
                .append("_")
                .append(adminInfo.getId())
                .append(fileName.substring(fileName.lastIndexOf("."), fileName.length()));
        File file = new File(newFileName.toString());
        if (file.exists()) {//文件存在就重新创建
            file.delete();
        }
        file = new File(newFileName.toString());
        file.createNewFile();
        InputStream is = items.get(0).getInputStream();
        //将原文件内容读取到目标文件
        OutputStream out = new FileOutputStream(file);
        try {
            int a = 0;
            while ((a = is.read()) != -1) {
                out.write(a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //流关闭
            try {
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JsonResult<List<List<String>>> data = ReadExcelUtil.readExcelInfo(file);
        if (data.getCode() != 200) {
            return new JsonResult<>(null, data.getCode(), data.getMsg());
        }
        if (EmptyUtils.isEmpty(userOrganizationDto)){
            return JsonResult.paramErrWithMsg("参数错误");
        }
        return service.addImportUserForOrganization(data.getData(), adminInfo.getEnterpriseId(),userOrganizationDto);
    }
}
